//
//  CZLoginViewController.swift
//  Weibo
//
//  Created by 董松 on 16/2/27.
//  Copyright © 2016年 董松. All rights reserved.
//

import UIKit
import AFNetworking


class CZLoginViewController: UIViewController ,UIWebViewDelegate{

    var webView: UIWebView?
    
    override func loadView() {
        
        //一定要注意，创建实例
        webView = UIWebView()
        //设置代理
        webView?.delegate = self
        //赋值
        view = webView
        
        print(view)
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
        
        //设置请求url
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(App_KEY)&redirect_uri=\(App_URL)&response_type=code")!
        
        //创建一个请求
        let request = NSURLRequest(URL: url)
        
        //加载请求
        webView?.loadRequest(request)
    }
    
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "auto")
    
    }
    //MARK:实现nav的按钮方法
    func dismiss(){
        dismissViewControllerAnimated(true) { () -> Void in
        
        }
    }

    func auto(){
        
        let js = "document.getElementById(\"userId\").value = \"itcast123456@hotmail.com\";document.getElementById(\"passwd\").value = \"itcast123456\";"
        
        webView?.stringByEvaluatingJavaScriptFromString(js)
    }
    
}

//把webview的代理方法写在这里

extension CZLoginViewController{
    func webViewDidStartLoad(webView: UIWebView) {
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //先判空
        if let url = request.URL?.absoluteString{
            
            if url.hasPrefix(App_URL){
                if let code = request.URL?.query {
                    print(code)
                    
                    let subCode = code.substringFromIndex("code=".endIndex)
                    print(subCode)
                    CZUserViewModel().loadToken(subCode, success: { () -> () in
                        //成功的回调
                        print("成功")
                        }, failure: { () -> () in
                            //失败的回调
                            print("失败")
                    })
                }
            }
        }
        return true
    }
}

//MARK:通过code来换取token
extension CZLoginViewController{
    
}

//MARK:通过token来获取用户信息
extension CZLoginViewController{
    
}























